define(['jquery', 'bootstrap', 'validator', 'aojie', 'upload','template'], function ($, undefined, Validator, Aojie, Upload,template) {
    var Form = {
        config:{
          field_list_tpl:'<div class="field_list_box_item"><input  type="text" name="{{name}}[{{index}}][key]" placeholder="键" class="form-control" value="{{row.key}}"> <input  type="text" name="{{name}}[{{index}}][value]" placeholder="值" class="form-control" value="{{row.value}}" > <button type="button" class="btn btn-danger btn-remove"><i class="fa fa-trash"></i> </button> </div>',
        },
        events: {
            validator: function (form, success, error, submit) {
                if (!form.is("form"))
                    return;
                //绑定表单事件
                form.validator($.extend({
                    validClass: 'has-success',
                    invalidClass: 'has-error',
                    bindClassTo: '.form-group',
                    formClass: 'n-default n-bootstrap',
                    msgClass: 'n-bottom',
                    stopOnError: true,
                    display: function (elem) {
                        var text = $(elem).closest('.form-group').find(".control-label").text().replace(/\:\：/, '');
                        if (text == '') {
                            var text = $(elem).attr('data-form-label');
                        }
                        return text;
                    },
                    dataFilter: function (data) {
                        if (data.code === 1) {
                            return data.msg ? {"ok": data.msg} : '';
                        } else {
                            return data.msg;
                        }
                    },
                    target: function (input) {
                        var target = $(input).data("target");
                        if (target && $(target).size() > 0) {
                            return $(target);
                        }
                        var $formitem = $(input).closest('.layui-form-item'),
                            $msgbox = $formitem.find('span.msg-box');
                        if (!$msgbox.length) {
                            return [];
                        }
                        return $msgbox;
                    },
                    valid: function (ret) {
                        var that = this, submitBtn = $(".layer-footer [type=submit]", form);
                        that.holdSubmit(true);
                        submitBtn.addClass("disabled");
                        //验证通过提交表单
                        var submitResult = Form.api.submit($(ret), function (data, ret) {
                            that.holdSubmit(false);
                            submitBtn.removeClass("disabled");
                            if (false === $(this).triggerHandler("success.form", [data, ret])) {
                                return false;
                            }
                            if (typeof success === 'function') {
                                if (false === success.call($(this), data, ret)) {
                                    return false;
                                }
                            }
                            var msg = ret.hasOwnProperty("msg") && ret.msg !== "" ? ret.msg : '操作完成';
                            parent.Toastr.success(msg);
                            parent.$(".btn-refresh").trigger("click");
                            var index = parent.layer.getFrameIndex(window.name);
                            parent.layer.close(index);
                            return false;
                        }, function (data, ret) {
                            that.holdSubmit(false);
                            if (false === $(this).triggerHandler("error.form", [data, ret])) {
                                return false;
                            }
                            submitBtn.removeClass("disabled");
                            if (typeof error === 'function') {
                                if (false === error.call($(this), data, ret)) {
                                    return false;
                                }
                            }
                        }, submit);
                        //如果提交失败则释放锁定
                        if (!submitResult) {
                            that.holdSubmit(false);
                            submitBtn.removeClass("disabled");
                        }
                        return false;
                    }
                }, form.data("validator-options") || {}));
                //移除提交按钮的disabled类
                $(".layer-footer [type=submit],.fixed-footer [type=submit],.normal-footer [type=submit]", form).removeClass("disabled");

            },
            webupload: function (form) {
                //绑定webupload上传元素事件
                if ($(".webupload", form).size() > 0) {
                    Upload.api.webuploader($(".webupload", form));
                }
            },
            datetimepicker: function (form) {
                if ($(".datetimepicker").size() > 0) {
                    require(['bootstrap-datetimepicker'], function () {
                        var options = {
                            format: 'YYYY-MM-DD HH:mm:ss',
                            icons: {
                                time: 'fa fa-clock-o',
                                date: 'fa fa-calendar',
                                up: 'fa fa-chevron-up',
                                down: 'fa fa-chevron-down',
                                previous: 'fa fa-chevron-left',
                                next: 'fa fa-chevron-right',
                                today: 'fa fa-history',
                                clear: 'fa fa-trash',
                                close: 'fa fa-remove'
                            },
                            showTodayButton: true,
                            showClose: true
                        };
                        $('.datetimepicker', form).parent().css('position', 'relative');
                        $('.datetimepicker', form).datetimepicker(options).on('dp.change', function (e) {
                            $(this, document).trigger("changed");
                        });
                    });
                }
            },

            field_list:function(form){
                if ($("textarea.field_list").size() > 0) {
                    //刷新textarea的值
                    var refresh = function(name){
                        var data = {};
                        var textarea = $("textarea[name='" + name + "']", form);
                        console.log(textarea);
                        var container = $(".field_list_box[data-name='" + name + "']");
                        var template = container.data("template");
                        $.each($("input,select,textarea", container).serializeArray(), function (i, j) {
                            var reg = /\[(\w+)\]\[(\w+)\]$/g;
                            var match = reg.exec(j.name);
                            if (!match)
                                return true;
                            match[1] = "x" + parseInt(match[1]);
                            if (typeof data[match[1]] == 'undefined') {
                                data[match[1]] = {};
                            }
                            data[match[1]][match[2]] = j.value;
                        });
                        var result = template ? [] : {};
                        $.each(data, function (i, j) {
                            if (j) {
                                if (!template) {
                                    if (j.key != '') {
                                        result[j.key] = j.value;
                                    }
                                } else {
                                    result.push(j);
                                }
                            }
                        });
                        textarea.val(JSON.stringify(result));
                    };
                    //监听文本框改变事件
                    $(document).on('change keyup changed', ".field_list_box input,.field_list_box textarea,.field_list_box select", function () {
                        refresh($(this).closest(".field_list_box").data("name"));
                    });
                    //追加控制
                    $(".field_list_box", form).on("click", ".btn-clone", function (e, row) {
                        var container = $(this).closest(".field_list_box");
                        var index = container.data("index");
                        var name = container.data("name");
                        var template_str = container.data("template");
                        var data = container.data();
                        index = index ? parseInt(index) : 0;
                        container.data("index", index + 1);
                        row = row ? row : {};
                        var vars = {index: index, name: name, data: data, row: row};
                        var html = template_str ? template(template_str, vars) : template.render(Form.config.field_list_tpl, vars);
                        $(this).before(html);
                    });
                    //移除控制
                    $(".field_list_box", form).on("click", ".btn-remove", function () {
                        var container = $(this).closest(".field_list_box");
                        $(this).closest('.field_list_box_item').remove();
                        refresh(container.data("name"));
                    });

                    //渲染数据&拖拽排序
                    $(".field_list", form).each(function () {
                        var container = this.closest('.field_list_box');
                        var textarea = $("textarea[name='" + $(this).data("name") + "']", form);
                        if (textarea.val() == '') {
                            return true;
                        }
                        var template = $(this).data("template");
                        var json = {};
                        try {
                            json = JSON.parse(textarea.val());
                        } catch (e) {
                        }
                        $.each(json, function (i, j) {
                            $(".btn-clone", container).trigger('click', template ? j : {
                                key: i,
                                value: j
                            });
                        });
                    });
                }

            },
            bindevent: function (form) {
            },
        },
        api: {
            submit: function (form, success, error, submit) {
                if (form.length === 0) {
                    Toastr.error("表单未初始化完成,无法提交");
                    return false;
                }
                if (typeof submit === 'function') {
                    if (false === submit.call(form, success, error)) {
                        return false;
                    }
                }
                var type = form.attr("method") ? form.attr("method").toUpperCase() : 'GET';
                type = type && (type === 'GET' || type === 'POST') ? type : 'GET';
                var url = form.attr("action");
                url = url ? url : location.href;
                var loading = form.attr('data-loading');
                loading = typeof loading == 'undefind' ? null : loading;
                //修复当存在多选项元素时提交的BUG
                var params = {};
                var multipleList = $("[name$='[]']", form);
                if (multipleList.length > 0) {
                    var postFields = form.serializeArray().map(function (obj) {
                        return $(obj).prop("name");
                    });
                    $.each(multipleList, function (i, j) {
                        if (postFields.indexOf($(this).prop("name")) < 0) {
                            params[$(this).prop("name")] = '';
                        }
                    });
                }
                Aojie.api.axios({
                    method: type,
                    url: url,
                    loading: loading,
                    data: form.serialize() + (Object.keys(params).length > 0 ? '&' + $.param(params) : ''),
                }, function (data, ret) {
                    $('.form-group', form).removeClass('has-success has-error');
                    if (typeof success === 'function') {
                        if (false === success.call(form, data, ret)) {
                            return false;
                        }
                    }
                }, function (data, ret) {
                    if (typeof error === 'function') {
                        if (false === error.call(form, data, ret)) {
                            return false;
                        }
                    }
                });
                return true;
            },

            bindevent: function (form, success, error, submit) {
                form = typeof form === 'object' ? form : $(form);
                var events = Form.events;
                events.bindevent(form);

                events.validator(form, success, error, submit);

                events.webupload(form);

                events.datetimepicker(form);

                events.field_list(form);
                /*  events.selectpicker(form);

                  events.daterangepicker(form);

                  events.selectpage(form);

                  events.cxselect(form);

                  events.citypicker(form);





                  events.faselect(form);

                  events.fieldlist(form);

                  events.slider(form);

                  events.switcher(form);*/
            },

        }


    };
    return Form;
})